package com.example.library.dialog;

import android.content.DialogInterface;
import android.databinding.DataBindingUtil;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.library.R;
import com.example.library.adapter.KnowledgePageAdapter;
import com.example.library.databinding.DialogCheckwordBinding;
import com.example.library.player.MyMediaPlayer;
import com.example.library.viewmodle.CheckWordDialogViewModel;
import com.lancoo.evaluate.api.EvaluateContext;
import com.lancoo.evaluate.api.OnEvaluatedCallback;
import com.lancoo.evaluate.bean.Evaluate;
import com.lancoo.evaluate.bean.EvaluateResult;
import com.orhanobut.logger.Logger;
import com.tt.CoreType;
import com.tt.lancoo.OnRecordCallback;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;

import static com.example.library.utils.DensityUtils.dp2px;

/**
 * Created by dadong on 2018/8/15.
 * Describe:
 */
public class KnowLedgeAnalysisDialog extends DialogFragment implements View.OnClickListener {

    DialogCheckwordBinding mBinding;
    CheckWordDialogViewModel mViewModel;
    MyMediaPlayer player;
    Toast toast;
    EvaluateContext mEvaluateContext;
    Evaluate mEvaluate;
    Handler handler = new Handler();
    ViewPager viewPager;
    TabLayout tabLayout;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.dialog_checkword, null, false);
        mBinding.setViewModel(mViewModel);
        return mBinding.getRoot();
    }

    @Override
    public void onActivityCreated(Bundle saveInstanceState) {
        super.onActivityCreated(saveInstanceState);
        init();
        player = new MyMediaPlayer();
        //英式发音
        mBinding.clEnglishExplanation.setOnClickListener(this);
        //美式发音
        mBinding.clAmericaExplanation.setOnClickListener(this);
        //录音评分
        mBinding.rlRecord.setOnClickListener(this);
        //回放
        mBinding.tvReplay.setOnClickListener(this);
        //关闭
        mBinding.ivClose.setOnClickListener(this);
        //tablayout + viewPager + recyclerView
        viewPager = mBinding.getRoot().findViewById(R.id.vp_example);
        tabLayout = mBinding.getRoot().findViewById(R.id.tab_example);
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.setOverScrollMode(TabLayout.MODE_SCROLLABLE);
        tabLayout.setSelectedTabIndicatorColor(getResources().getColor(R.color.theme_blue));
        initTabLayout();
//        tabLayout.post(new Runnable() {
//            @Override
//            public void run() {
//                setIndicator(tabLayout, dp2px(getContext(), 0), dp2px(getContext(), 0));
//            }
//        });
        reflex(tabLayout);
    }

    private void initTabLayout() {
        viewPager.setAdapter(new KnowledgePageAdapter(getChildFragmentManager(), mViewModel));
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private void playBack() {
        if (mEvaluate != null) {
            if (mEvaluate.getPcmPath() != null) {
                mBinding.tvReplay.setClickable(false);
                player.setPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer MediaPlayer) {
                        player.start();
                    }
                });

                player.setCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer MediaPlayer) {
                        MediaPlayer.reset();
                        mBinding.tvReplay.setClickable(true);
                    }
                });

                player.setDataSource(mEvaluate.getWavPath());
            }
        }
    }

    private void onEvaluate() {
        ArrayList<Evaluate> evaluates = new ArrayList<>();
        if (mEvaluate != null) {
            evaluates.add(mEvaluate);
            Logger.d(mEvaluate.getWavPath());
        }

        mEvaluateContext.setOnEvaluatedCallback(new OnEvaluatedCallback() {
            @Override
            public void onEvaluated(ArrayList<EvaluateResult> evaluateResults) {
                EvaluateResult evaluateResult = evaluateResults.get(0);
                mBinding.bcRecordWave.stop();
                mBinding.groupResult.setVisibility(View.VISIBLE);
                mBinding.tvEvaluateScore.setText(evaluateResult.getScore() + "");
                mBinding.bcRecordWave.setVisibility(View.GONE);
            }
        });

        mEvaluateContext.startEvaluate(evaluates);
    }

    private void englishPronunciation() {
        mBinding.clEnglishExplanation.setClickable(false);
        player.setPreparedListener(new MediaPlayer.OnPreparedListener() {

            @Override
            public void onPrepared(MediaPlayer mp) {
                player.start();
            }
        });
        player.setCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mp.reset();
                mBinding.clEnglishExplanation.setClickable(true);
            }
        });
        player.setDataSource(mViewModel.englishPronunciation.get());
    }

    private void americaPronunciation() {
        mBinding.clAmericaExplanation.setClickable(false);
        player.setPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer MediaPlayer) {
                player.start();
            }
        });
        player.setCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer MediaPlayer) {
                MediaPlayer.reset();
                mBinding.clAmericaExplanation.setClickable(true);
            }
        });
        player.setDataSource(mViewModel.americanPronunciation.get());
    }

    @Override
    public void onStart() {
        super.onStart();
        Window window = getDialog().getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.gravity = Gravity.CENTER;
        lp.width = dp2px(getActivity(), 356);
        lp.height = dp2px(getActivity(), 326);
        window.setAttributes(lp);
        window.setBackgroundDrawable(null);
        getDialog().setCancelable(false);
    }

//    @Override
//    public boolean onTouch(View v, MotionEvent event) {
//        switch (event.getAction()) {
//            case MotionEvent.ACTION_DOWN:
//                prepareRecord();
//                return true;
//
//            case MotionEvent.ACTION_UP:
//            case MotionEvent.ACTION_CANCEL:
//                mBinding.tvRecord.setText("停止录音");
//                mEvaluateContext.stopRecord();
//                return true;
//        }
//        return false;
//    }

    //准备录音
    private void prepareRecord() {
        String path = Environment.getExternalStorageDirectory().getAbsolutePath()
                + File.separator + "record.wav";
        File wav = new File(path);
        if (wav.exists()) {
            wav.delete();
        } else {
            wav.mkdir();
        }
        mEvaluateContext.startRecord(
                wav,
                new OnRecordCallback() {
                    @Override
                    public void onRecordStart() {
                        Log.e("My", "onRecordStart================");
                        handler.postDelayed(runnable, 5000);
                    }

                    @Override
                    public void onRecordEnd(String wavPath, String pcmPath) {
                        mEvaluate.setWavPath(wavPath);
                        mEvaluate.setPcmPath(pcmPath);
                        Log.e("My", wavPath + "<================>" + pcmPath);
                        onEvaluate();
                    }

                    @Override
                    public void onFailure(String msg) {
                        Log.e("My", "onFailure================>" + msg);
                    }
                }
        );
        // mBinding.tvRecord.setText("长按录音");
    }

    public void show(FragmentManager manager) {
        manager.executePendingTransactions();
        if (!isAdded()) {
            show(manager, KnowLedgeAnalysisDialog.class.getName());
        }
    }

    public void setMViewModel(CheckWordDialogViewModel viewModel) {
        this.mViewModel = viewModel;
    }


    private void init() {
        mEvaluateContext = new EvaluateContext(getActivity(), "knowledge_analysis");
        mEvaluateContext.setOnContextInitCallback(null);
        mEvaluate = new Evaluate();
        mEvaluate.setCoreType(CoreType.EN_WORD_EVAL);
        mEvaluate.setRefText(mViewModel.knowledge.get());
        mEvaluate.setTotalScore(100);
    }

    public void showToast(String msg) {
        if (toast == null) {
            toast = Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT);
        }
        toast.setText(msg);
        toast.show();
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        //资源的回收
        if (player != null) {
            if (player.isPlaying()) {
                player.stop();
            }
            player.release();
        }
        if (mEvaluateContext != null) {
            mEvaluateContext.onDestroy();
            mEvaluate = null;
            mEvaluateContext = null;
        }
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            mBinding.bcRecordWave.stop();
            mEvaluateContext.stopRecord();
        }
    };

    Runnable animRunnable = new Runnable() {
        @Override
        public void run() {
            mBinding.bcRecordWave.start();
        }
    };

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.rl_record) {
            mBinding.tvReplay.setVisibility(View.VISIBLE);
            mBinding.bcRecordWave.setVisibility(View.VISIBLE);
            mBinding.groupResult.setVisibility(View.GONE);
            prepareRecord();
            //准备时间1.5s
            mBinding.bcRecordWave.start();
//            handler.postDelayed(animRunnable, 1500);
        } else if (v.getId() == R.id.cl_english_explanation) {
            englishPronunciation();
        } else if (v.getId() == R.id.cl_america_explanation) {
            americaPronunciation();
        } else if (v.getId() == R.id.tv_replay) {
            playBack();
        } else if (v.getId() == R.id.iv_close) {
            getDialog().dismiss();
            getDialog().cancel();
        }
    }

    public static void reflex(final TabLayout tabLayout) {
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                try {
                    Field mTabStripField = tabLayout.getClass().getDeclaredField("mTabStrip");
                    mTabStripField.setAccessible(true);
                    LinearLayout mTabStrip = (LinearLayout) mTabStripField.get(tabLayout);
                    int dp10 = dp2px(tabLayout.getContext(), 10);
                    for (int i = 0; i < mTabStrip.getChildCount(); i++) {
                        View tabView = mTabStrip.getChildAt(i);
                        Field mTextViewField = tabView.getClass().getDeclaredField("mTextView");
                        mTextViewField.setAccessible(true);
                        TextView mTextView = (TextView) mTextViewField.get(tabView);
                        tabView.setPadding(0, 0, 0, 0);
                        int width = 0;
                        width = mTextView.getWidth();
                        if (width == 0) {
                            mTextView.measure(0, 0);
                            width = mTextView.getMeasuredWidth();
                        }
                        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                        params.width = width;
                        params.leftMargin = dp10;
                        params.rightMargin = dp10;
                        tabView.setLayoutParams(params);
                        tabView.invalidate();
                    }
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
